import React, {useState, useEffect, useMemo} from 'react';
import { WaitUmd, is_empty, Btn, obj_str, loc, PanelFind, Ret, Title, filter_row, show_mt, InfoDlg, useCmd, useHigh, GridTable } from 'sui';
import { load_col } from 'stuff/cmd';
import { ToolStep } from './step';

const ToolView = ({ cur, hreturn, no_acc }) => {
    const [open_info, openInfo] = useState(false);
    const [col, setCol] = useState();
    const [high] = useHigh(200, 100);
    const umd = useCmd("bom/list", null, { k: obj_str(cur, "sn") });

    useEffect(() => {
        load_col(setCol, "step");
    }, []);

    const getRow = useMemo(() => {
        if (is_empty(col)) {
            return null;
        }

        const lst = col.map(d => d.sn);
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter, col]);

    const hret = () => {
        umd.reload();
        umd.hreturn();
    };

    if (umd.isFin("step")) {
        return <ToolStep hreturn={hret} cur={cur}/>;
    }

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
        ];

        col.forEach(d => show_mt(tmp, d, 110));

        return tmp;
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn className="ml-4" hcmd={() => umd.pact(null, null, "step")} color="green" disabled={no_acc("na")}>{loc("l_149")}</Btn>
            <Ret className="ml-4" hcmd={hreturn}/>
        </div>
    );

    const Left = () => <Title mod={obj_str(cur, "sn")} sub={loc("l_148")}/>;

    return (
        <div className="flex flex-col">
            <PanelFind left={<Left/>} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={getCol()} row={getRow}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_855")} hcmd={() => umd.endWait()}/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {ToolView};
